package com.tn.tcp;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.tn.socket.SocketProperties;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.*;

public class CardMachineParamUtil {
    public final static String ACT = "ACT";

    public static void main(String[] args) {
        String str = "ACT:login;USABLE_BATTERY:0;EMPTY_SLOT_COUNT:9;TOTAL:0;USABLE_BATTERY_NEW:1_0#2_0#3_0#4_0;L_PD:0;MAC:866569061176274;CCID: 89860621290083177151;CompileData:Jan-19-2022;ROUTE:2G;HeartCycle:90;BorrowPowerStep:60;CompileTime:14-48-48;DFLT_DOMAIN:test.zhenyoukeji.com;SendFail:;ResetCause:;NetHard:;NetSoft:A;DSP:;CHKSUM:972565E3";
        Map<String, String> map = formatParam(str);
        Console.log(map);
    }
    public static Map<String,String> formatParam(String data){
        if(StrUtil.isBlank(data)){
            return null;
        }
        Map<String, String> strMap = new HashMap<>();
        List<String> ack = StrUtil.split(data,";");
        for(String value : ack){
            if(StrUtil.isBlank(value)){
                continue;
            }
            String[] mapArr = value.split(":");
            if(mapArr.length < 2){
                continue;
            }
            strMap.put(mapArr[0],mapArr[1]);
        }
        return strMap;
    }

    public static String getIntranetIp(){
        try {
            InetAddress addr = InetAddress.getLocalHost();
            String hostname = addr.getHostAddress();
            return hostname;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获得外网IP
     * @return 外网IP
     */
    public static String getInternetIp(){
        try{
            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            Enumeration<InetAddress> addrs;
            while (networks.hasMoreElements())
            {
                addrs = networks.nextElement().getInetAddresses();
                while (addrs.hasMoreElements())
                {
                    ip = addrs.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && ip.isSiteLocalAddress()
                            && !ip.getHostAddress().equals(getIntranetIp()))
                    {
                        return ip.getHostAddress();
                    }
                }
            }
            // 如果没有外网IP，就返回内网IP
            return getIntranetIp();
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    public static Long getUnixTime(){
        return Calendar.getInstance().getTimeInMillis()/1000L;
    }

    // 统一返回“错误”
    public static String cmBackError(){
        return "ERRCODE:1000;ERRMSG:none;";
    }

    // 登录返回
    public static String cmBackLogin(String stationId) {
        return new StringBuilder("BINDADDRESS:1;STATIONID:").append(stationId).append(";").toString();
    }

    public static String cmBackSyncSetting(SocketProperties socketProperties, int heartBeatTime) {
        return new StringBuilder("TIME:").append(CardMachineParamUtil.getUnixTime())
                .append(";DOMAIN:").append(socketProperties.isUseInternet()?socketProperties.getInternetIp(): CardMachineParamUtil.getInternetIp())
                .append(";IP:").append(socketProperties.isUseInternet()?socketProperties.getInternetIp(): CardMachineParamUtil.getInternetIp())
                .append(";PORT:").append(socketProperties.getPort())
                .append(";BPS:30;CHECKUPDATEDELAY:1;SOFT_VER:81;")
                .append("FILE_NAME:null")
                .append(";HEARTBEAT:").append(heartBeatTime)
                .toString();
    }

    public static String cmBackHeartBeat() {
        return "ERRCODE:0;ERRMSG:none;ACK:heartbeat";
    }

    // 指令“弹指定槽位的集卡”：槽位，秒时间戳
    public static String cmCmdPopupCard(String slot){
        return new StringBuilder("EVENT_CODE:55;SLOT:").append(slot).append(";MSG_ID:").append(getUnixTime()).toString();
    }

    // 确认响应“发卡机对弹卡指令的回复”
    public static String cmBackPopupConfirm(String slot) {
        return new StringBuilder("RRCODE:55;ERRMSG:None;SLOT:").append(slot).append(";ACK:popup_confirm").toString();
    }

    public static String cmBackReturnBack(String cardId) {
        return new StringBuilder("ERRCODE:0;ERRMSG:none;ID:").append(cardId).append(";ACK:").append("return_back").toString();
    }

    public static class CMConsts {
        public static final int CARD_MACHINE_TYPE_IN = 2; // 进闸发卡机
        public static final int CARD_MACHINE_TYPE_OUT = 1; // 出闸发卡机
        public static final String ACT = "ACT";
        public static final String USABLE_BATTERY = "USABLE_BATTERY";
        public static final String TOTAL = "TOTAL";
        public static final String MAC = "MAC";
        public static final String CCID = "CCID";
        public static final String STATIONID = "STATIONID";
        public static final String ID = "ID";
        public static final String ORDERID = "ORDERID";
        public static final String SLOT = "SLOT";
        public static final String CHKSUM = "CHKSUM";

        public static final String CARD_MACHINE_ACT_LOGIN = "login"; // 登录
        public static final String CARD_MACHINE_ACT_SYNC_SETTING = "sync_setting"; // 同步设置
        public static final String CARD_MACHINE_ACT_HEART_BEAT = "heartbeat"; // 心跳
        public static final String CARD_MACHINE_ACT_RETURN_BACK = "return_back"; // 还卡
        public static final String CARD_MACHINE_ACT_POPUP_CONFIRM = "popup_confirm"; // 弹卡回复
        public static final int POPUP_CARD_NULL = 0; // 无
        public static final int POPUP_CARD_BEGIN = 1; // 开始
        public static final int POPUP_CARD_SUCCESS = 2; // 成功
        public static final int POPUP_CARD_FAIL = 3; // 失败
    }
    // 登录
    // ACT:login;USABLE_BATTERY:0;EMPTY_SLOT_COUNT:9;TOTAL:0;USABLE_BATTERY_NEW:1_0#2_0#3_0#4_0;L_PD:0;MAC:865242055704466;CCID: 89860621290083177151;CompileData:Jan-19-2022;ROUTE:2G;HeartCycle:90;BorrowPowerStep:60;CompileTime:14-48-48;DFLT_DOMAIN:test.zhenyoukeji.com;SendFail:;ResetCause:;NetHard:;NetSoft:A;DSP:;CHKSUM:972565E3
    // ACT:login;USABLE_BATTERY:0;EMPTY_SLOT_COUNT:9;TOTAL:0;USABLE_BATTERY_NEW:1_0#2_0#3_0#4_0;L_PD:0;MAC:867542055884814;CCID: 89860621290083177151;CompileData:Jan-19-2022;ROUTE:2G;HeartCycle:90;BorrowPowerStep:60;CompileTime:14-48-48;DFLT_DOMAIN:test.zhenyoukeji.com;SendFail:;ResetCause:;NetHard:;NetSoft:A;DSP:;CHKSUM:972565E3
    // 心跳
    // ACT:heartbeat;SLOTSTATUS:03-03-03-03-03-03-03-03-03-;USABLE_BATTERY:9;EMPTY_SLOT_COUNT:0;TOTAL:9;USABLE_BATTERY_NEW:1_0#2_0#3_0#4_9;TIMESTAMP:1659144599;STATIONID:MD2012071503;STATUS:0;CH:S1,1,100,5705015076|S2,1,100,5705009722|S3,1,100,5705007642|S4,1,100,5705006946|S5,1,100,5705015390|S6,1,100,5705009720|S7,1,100,5705015895|S8,1,100,5705009604|S9,1,100,5705009707|;2G_RSSI: 31;CHKSUM:D0AF2EE2
    // ACT:heartbeat;SLOTSTATUS:03-03-03-00-00-00-00-00-00-;USABLE_BATTERY:3;EMPTY_SLOT_COUNT:6;TOTAL:3;USABLE_BATTERY_NEW:1_0#2_0#3_0#4_3;TIMESTAMP:73;STATIONID:MD2202180031;STATUS:0;CH:S1,1,100,6066050073|S2,1,100,6021120059|S3,1,100,5705009574|S4,0,0,0000000000|S5,0,0,0000000000|S6,0,0,0000000000|S7,0,0,0000000000|S8,0,0,0000000000|S9,0,0,0000000000|;2G_RSSI: 22;CHKSUM:87F93A0C
    // 弹卡响应
    // ACT:popup_confirm;USABLE_BATTERY:4;EMPTY_SLOT_COUNT:5;TOTAL:4;USABLE_BATTERY_NEW:1_0#2_0#3_0#4_4;STATUS:1;DEV_INFO:0000000037000000007800;TIMESTAMP:213;STATIONID:MD2012071503;2G_RSSI: 22;ROUTE:2G;CHKSUM:D70EB362;SLOT:1
    // 还卡
    // ACT:return_back;USABLE_BATTERY:0;EMPTY_SLOT_COUNT:7;TOTAL:2;USABLE_BATTERY_NEW:1_0#2_0#3_0#4_0;ID:6066050073;KEY:1;TIME:58;TIMESTAMP:61;STATIONID:MD2012071503;DEV_INFO:0000800000000000008000;ROUTE:2G;CABLE:0;C:0;POWER:100;VOLTAGE:4430;SLOT:1;CHKSUM:111EC061

}
